import pymysql
import traceback  # 可以将报错信息打印在控制台上面

class DB:
    def __init__(self,user,password,host,database):
        self.user=user
        self.password=password
        self.host=host
        self.database=database
    def connect(self):
        self.db=pymysql.connect(user=self.user,password=self.password,host=self.host,database=self.database,cursorclass =
        pymysql.cursors.DictCursor)
        self.cursor = self.db.cursor()   # 通过数据库对象创建游标

        def close(self):  #关闭
            self.cursor.close()
            self.db.close()
        def search(self, type: int, sql): #查看
            self.connect()
            result = None
            if type == 1:
                try:
                    self.cursor.execute(sql)
                    result = self.cursor.fetchone()
                    self.close()
                    return result
                except:
                    self.db.rollback()
                    traceback.print_exc()
                    return result
            elif type==2:
                try:
                    self.cursor.execute(sql)
                    result = self.cursor.fetchall()
                    self.close()
                    return result
                except:
                    self.db.rollback()
                    traceback.print_exc()
                    return result

        def __edit(self, sql):
            self.connect()
            try:
                self.cursor.execute(sql)
                self.db.commit()
                self.close()
            except:
                self.db.rollback()
                traceback.print_exc()

        def insert(self, sql):  # 新增
            self.__edit(sql)

        def delete(self, sql):  # 删除
            self.__edit(sql)

        def update(self, sql):  # 更新
            self.__edit(sql)
if __name__ == '__main__':
    # 创建d1对象
    d1 = DB(user='root',password='123456',host='8.136.106.114',database='zuoye')
    # 查询
    # print(d1.search(2, "select * from student"))
    # 新增
    # d1.insert("insert into student(name,phone,address) values('李四','123','辽宁锦州')")
    # 查询
    # print(d1.search(1,"select * from student where name='李四'"))
    # 删除
    # d1.delete("delete from student where id=7")

    # # 更新操作
    # d1.update("update student set name='张鑫plus' where name='张鑫'")
    # # 查询
    # print(d1.search(2, "select * from student"))


